<template>
  <div>APP!</div>
  <div>计算属性和监听</div>
  <fieldset>
    <legend>姓名操作</legend>
    姓氏: <input type="text" placeholder="请输入姓氏" v-model="user.firstName"><br/>
    名字: <input type="text" placeholder="请输入名字" v-model="user.lastName">
  </fieldset>
  <fieldset>
    <legend>计算属性和监听演示</legend>
    姓名: <input type="text" placeholder="请输入姓名" v-model="fullName"><br/>
    姓名: <input type="text" placeholder="请输入姓名" v-model="fullName2"><br/>
    姓名: <input type="text" placeholder="请输入姓名" v-model="fullName3">
  </fieldset>
</template>

<script lang="ts">
import {defineComponent, reactive, computed, watch, ref,watchEffect} from 'vue';

export default defineComponent({
  name: 'App',
  components: {},
  setup() {
    const user = reactive({
      firstName: '东方',
      lastName: '不败'
    })
//computed只传入一个参数 表示getter
    const fullName = computed(() => {
      return user.firstName + '_' + user.lastName
    })

    const fullName2 = computed({
      get() {
        return user.firstName + '_' + user.lastName
      },
      set(v: string) {
        const names = v.split('_')
        user.firstName = names[0];
        user.lastName = names[1]
      }
    })
    let fullName3 = ref('')
    // watch(user, ({firstName, lastName}) => {
    //   fullName3.value = firstName + '_' + lastName
    // }, {immediate:true,deep:true})
    watchEffect(()=>{
      fullName3.value = user.firstName+'_'+user.lastName
    })

    watchEffect(()=>{
      const names = fullName3.value.split('_');
      user.firstName  = names[0];
      user.lastName = names[1]
    })

    //监听多个数据
    // watch([()=>user.firstName,()=>user.lastName,fullName3],()=>{
    //   console.log('####')
    // })
    watch([user,fullName3],()=>{
      console.log('####')
    })
    return {
      user, fullName, fullName2, fullName3
    }
  }
});
</script>

<style>

</style>
